<template>
    <div class="level-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑等级' : '新增等级' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="levelFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="level-form"
                >
                    <div class="form-layout">
                        <!-- 左侧表单 -->
                        <div class="form-left">
                            <!-- 语言代码 -->
                            <el-form-item label="中英文:" prop="language">
                                <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                                    <el-option label="中文" value="zh-CN" />
                                    <el-option label="英文" value="en-US" />
                                </el-select>
                            </el-form-item>

                            <!-- 等级代码 -->
                            <el-form-item label="等级代码:" prop="levelCode">
                                <el-input
                                    v-model="formData.levelCode"
                                    placeholder="输入等级代码"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 等级名称 -->
                            <el-form-item label="等级名称:" prop="levelName">
                                <el-input
                                    v-model="formData.levelName"
                                    placeholder="输入等级名称"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 会员等级 -->
                            <el-form-item label="会员等级:" prop="memberLevel">
                                <el-input-number
                                    v-model="formData.memberLevel"
                                    :min="1"
                                    :max="999"
                                    placeholder="会员等级"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 成长值 -->
                            <el-form-item label="成长值:" prop="growthValue">
                                <el-input-number
                                    v-model="formData.growthValue"
                                    :min="0"
                                    :max="999999"
                                    placeholder="输入成长值"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 消费金额 -->
                            <el-form-item label="消费金额:" prop="consumptionAmount">
                                <el-input-number
                                    v-model="formData.consumptionAmount"
                                    :min="0"
                                    :precision="2"
                                    placeholder="消费金额达到升级"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 会员权益 -->
                            <el-form-item label="会员权益:" prop="memberBenefits">
                                <div class="benefits-section">
                                    <div class="benefit-item">
                                        <el-checkbox v-model="formData.benefits.qa">问答</el-checkbox>
                                        <el-input v-model="formData.benefits.qaDiscount" placeholder="" style="width: 80px; margin-left: 10px" />
                                        <span style="margin-left: 5px">折</span>
                                    </div>
                                    <div class="benefit-item">
                                        <el-checkbox v-model="formData.benefits.products">商品</el-checkbox>
                                        <el-input v-model="formData.benefits.productsDiscount" placeholder="" style="width: 80px; margin-left: 10px" />
                                        <span style="margin-left: 5px">折</span>
                                    </div>
                                    <div class="benefit-item">
                                        <el-checkbox v-model="formData.benefits.services">服务</el-checkbox>
                                        <el-input v-model="formData.benefits.servicesDiscount" placeholder="" style="width: 80px; margin-left: 10px" />
                                        <span style="margin-left: 5px">折</span>
                                    </div>
                                    <div class="benefit-item">
                                        <el-checkbox v-model="formData.benefits.coupon">优惠券</el-checkbox>
                                        <el-button type="primary" @click="openCouponDialog" :disabled="!formData.benefits.coupon">选择优惠券</el-button>
                                    </div>
                                    <div class="benefit-item">
                                        <el-checkbox v-model="formData.benefits.propCoupon">道具券</el-checkbox>
                                        <el-button type="primary" @click="openPropDialog" :disabled="!formData.benefits.propCoupon">选择道具券</el-button>
                                    </div>
                                </div>
                            </el-form-item>

                            <!-- 已选择的优惠券表格 -->
                            <el-form-item v-if="formData.benefits.coupon" label="已选优惠券:">
                                <el-table :data="formData.selectedCoupons" border style="width: 100%">
                                    <el-table-column type="index" label="序号" width="80" align="center" />
                                    <el-table-column prop="name" label="名称" />
                                    <el-table-column prop="quantity" label="数量" width="120" align="center" />
                                    <el-table-column label="操作" width="100" align="center">
                                        <template #default="{ $index }">
                                            <el-button type="danger" size="small" @click="removeCoupon($index)">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>

                            <!-- 已选择的道具券表格 -->
                            <el-form-item v-if="formData.benefits.propCoupon" label="已选道具券:">
                                <el-table :data="formData.selectedProps" border style="width: 100%">
                                    <el-table-column type="index" label="序号" width="80" align="center" />
                                    <el-table-column prop="name" label="名称" />
                                    <el-table-column prop="quantity" label="数量" width="120" align="center" />
                                    <el-table-column label="操作" width="100" align="center">
                                        <template #default="{ $index }">
                                            <el-button type="danger" size="small" @click="removeProp($index)">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>


                        </div>

                    </div>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 优惠券选择对话框 -->
        <el-dialog
            v-model="couponDialogVisible"
            title="选择优惠券"
            width="550px"
        >
            <el-table :data="couponList" v-loading="couponLoading" border>
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column label="选择" width="80" align="center">
                    <template #default="{ row }">
                        <el-checkbox 
                            v-model="row.selected"
                            @change="handleCouponCheck(row)"
                        >
                        </el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" align="center"/>
                <el-table-column label="数量" width="150">
                    <template #default="{ row }">
                        <el-input-number
                            v-model="row.quantity"
                            :min="1"
                            :max="999"
                            controls-position="right"
                            style="width: 120px"
                            :disabled="!row.selected"
                        />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button @click="couponDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmCouponSelection">确定</el-button>
            </template>
        </el-dialog>

        <!-- 道具券选择对话框 -->
        <el-dialog
            v-model="propDialogVisible"
            title="选择道具券"
            width="550px"
        >
            <el-table :data="propList" v-loading="propLoading" border>
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column label="选择" width="80" align="center">
                    <template #default="{ row }">
                        <el-checkbox 
                            v-model="row.selected"
                            @change="handlePropCheck(row)"
                        >
                        </el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" align="center"/>
                <el-table-column label="数量" width="150">
                    <template #default="{ row }">
                        <el-input-number
                            v-model="row.quantity"
                            :min="1"
                            :max="999"
                            controls-position="right"
                            style="width: 120px"
                            :disabled="!row.selected"
                        />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button @click="propDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmPropSelection">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getEnabledCoupons } from '@/api/member/coupon'
import { getPropList } from '@/api/member/props'
import { createMemberLevel, updateMemberLevel, getMemberLevelDetail } from '@/api/member/member-level'

const route = useRoute()
const router = useRouter()

// 表单引用
const levelFormRef = ref<FormInstance>()

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 优惠券对话框
const couponDialogVisible = ref(false)
const couponLoading = ref(false)
const couponList = ref<any[]>([])

// 道具券对话框
const propDialogVisible = ref(false)
const propLoading = ref(false)
const propList = ref<any[]>([])

// 表单数据
const formData = reactive({
    levelCode: '',
    levelName: '',
    memberLevel: 1,
    growthValue: 0,
    consumptionAmount: 0,
    sortOrder: '',
    language: 'zh-CN',
    consumptionAmountDesc: '',
    benefits: {
        qa: false,
        qaDiscount: '',
        products: false,
        productsDiscount: '',
        services: false,
        servicesDiscount: '',
        coupon: false,
        propCoupon: false
    },
    selectedCoupons: [],
    selectedProps: []
})

// 表单验证规则
const formRules = reactive<FormRules>({
    levelCode: [
        { required: true, message: '请输入等级代码', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
    ],
    levelName: [
        { required: true, message: '请输入等级名称', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在1到100个字符', trigger: 'blur' }
    ],
    memberLevel: [
        { required: true, message: '请输入会员等级', trigger: 'blur' },
        { type: 'number', min: 1, message: '会员等级必须大于0', trigger: 'blur' }
    ],
    growthValue: [
        { required: true, message: '请输入成长值', trigger: 'blur' },
        { type: 'number', min: 0, message: '成长值不能小于0', trigger: 'blur' }
    ],
    consumptionAmount: [
        { required: true, message: '请输入消费金额', trigger: 'blur' },
        { type: 'number', min: 0, message: '消费金额不能小于0', trigger: 'blur' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ]
})

// 取消操作
const handleCancel = () => {
    router.go(-1)
}

// 处理benefits字段，转换为数组格式
const processBenefits = () => {
    const benefits: any[] = []
    
    // 处理问答权益
    if (formData.benefits.qa && formData.benefits.qaDiscount) {
        benefits.push({
            benefitType: 1,
            benefitId: '',
            benefitName: '问答',
            discountRate: formData.benefits.qaDiscount
        })
    }
    
    // 处理商品权益
    if (formData.benefits.products && formData.benefits.productsDiscount) {
        benefits.push({
            benefitType: 2,
            benefitId: '',
            benefitName: '商品',
            discountRate: formData.benefits.productsDiscount
        })
    }
    
    // 处理服务权益
    if (formData.benefits.services && formData.benefits.servicesDiscount) {
        benefits.push({
            benefitType: 3,
            benefitId: '',
            benefitName: '服务',
            discountRate: formData.benefits.servicesDiscount
        })
    }
    
    // 处理优惠券权益
    if (formData.benefits.coupon && formData.selectedCoupons.length > 0) {
        formData.selectedCoupons.forEach((coupon: any) => {
            benefits.push({
                benefitType: 4,
                benefitId: coupon.id,
                benefitName: coupon.name,
                discountRate: coupon.quantity
            })
        })
    }
    
    // 处理道具权益
    if (formData.benefits.propCoupon && formData.selectedProps.length > 0) {
        formData.selectedProps.forEach((prop: any) => {
            benefits.push({
                benefitType: 5,
                benefitId: prop.id,
                benefitName: prop.name,
                discountRate: prop.quantity
            })
        })
    }
    
    return benefits
}

// 提交表单
const handleSubmit = async () => {
    if (!levelFormRef.value) return

    try {
        await levelFormRef.value.validate()
        
        // 处理benefits字段
        const benefits = processBenefits()
        
        // 构建提交数据
        const submitData = {
            levelCode: formData.levelCode,
            levelName: formData.levelName,
            memberLevel: formData.memberLevel,
            growthValue: formData.growthValue,
            consumptionAmount: formData.consumptionAmount,
            sortOrder: formData.sortOrder,
            language: formData.language,
            consumptionAmountDesc: formData.consumptionAmountDesc,
            benefits: benefits
        }
        
        console.log('提交的数据:', submitData)
        console.log('处理后的benefits:', benefits)
        
        let res: any
        if (isEdit.value) {
            // 编辑模式
            res = await updateMemberLevel(submitData)
        } else {
            // 新增模式
            res = await createMemberLevel(submitData)
        }
        
        const responseData = res as any
        if (responseData && responseData.code === 200) {
            ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
            setTimeout(() => {
                router.push('/level-list')
            }, 1000)
        } else {
            const errorMsg = (responseData && responseData.msg) || (isEdit.value ? '编辑失败' : '新增失败')
            ElMessage.error(errorMsg)
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('请检查表单信息')
    }
}

// 移除优惠券
const removeCoupon = (index: number) => {
    formData.selectedCoupons.splice(index, 1)
}

// 移除道具
const removeProp = (index: number) => {
    formData.selectedProps.splice(index, 1)
}

// 打开优惠券弹窗
const openCouponDialog = async () => {
    couponDialogVisible.value = true
    await loadCouponList()
    // 反显已选择的数据
    setCouponSelected()
}

// 打开道具券弹窗
const openPropDialog = async () => {
    propDialogVisible.value = true
    await loadPropList()
    // 反显已选择的数据
    setPropSelected()
}

// 设置优惠券选中状态
const setCouponSelected = () => {
    if (formData.selectedCoupons.length > 0) {
        couponList.value.forEach(item => {
            const selected = formData.selectedCoupons.find(selected => selected.id === item.id)
            if (selected) {
                item.selected = true
                item.quantity = selected.quantity
            }
        })
    }
}

// 设置道具券选中状态
const setPropSelected = () => {
    if (formData.selectedProps.length > 0) {
        propList.value.forEach(item => {
            const selected = formData.selectedProps.find(selected => selected.id === item.id)
            if (selected) {
                item.selected = true
                item.quantity = selected.quantity
            }
        })
    }
}

// 加载优惠券列表
const loadCouponList = async () => {
    couponLoading.value = true
    try {
        const res = await getEnabledCoupons()
        const responseData = res as any
        
        if (responseData && responseData.code === 200) {
            couponList.value = responseData.data.records.map((item: any) => ({
                id: item.id,
                name: item.name,
                quantity: 1,
                selected: false
            }))
        } else {
            ElMessage.error('获取优惠券列表失败')
            couponList.value = []
        }
    } catch (error) {
        console.error('获取优惠券列表失败:', error)
        ElMessage.error('获取优惠券列表失败')
        couponList.value = []
    } finally {
        couponLoading.value = false
    }
}

// 加载道具列表
const loadPropList = async () => {
    propLoading.value = true
    try {
        const res = await getPropList({})
        const responseData = res as any
        
        if (responseData && responseData.code === 200 && responseData.data) {
            propList.value = responseData.data.map((item: any) => ({
                id: item.id,
                name: item.propName,
                quantity: 1,
                selected: false
            }))
        } else {
            ElMessage.error('获取道具列表失败')
            propList.value = []
        }
    } catch (error) {
        console.error('获取道具列表失败:', error)
        ElMessage.error('获取道具列表失败')
        propList.value = []
    } finally {
        propLoading.value = false
    }
}

// 处理优惠券选择
const handleCouponCheck = (row: any) => {
    if (!row.selected) {
        row.quantity = 1
    }
}

// 处理道具选择
const handlePropCheck = (row: any) => {
    if (!row.selected) {
        row.quantity = 1
    }
}

// 确认优惠券选择
const confirmCouponSelection = () => {
    const selectedCoupons = couponList.value.filter(item => item.selected && item.quantity > 0)
    if (selectedCoupons.length > 0) {
        formData.selectedCoupons = selectedCoupons.map(item => ({
            id: item.id,
            name: item.name,
            quantity: item.quantity
        }))
        console.log('选择的优惠券:', formData.selectedCoupons)
        console.log('优惠券复选框状态:', formData.benefits.coupon)
        ElMessage.success(`已选择 ${selectedCoupons.length} 个优惠券`)
        couponDialogVisible.value = false
    } else {
        ElMessage.warning('请选择优惠券并设置数量')
    }
}

// 确认道具选择
const confirmPropSelection = () => {
    const selectedProps = propList.value.filter(item => item.selected && item.quantity > 0)
    if (selectedProps.length > 0) {
        formData.selectedProps = selectedProps.map(item => ({
            id: item.id,
            name: item.name,
            quantity: item.quantity
        }))
        console.log('选择的道具券:', formData.selectedProps)
        console.log('道具券复选框状态:', formData.benefits.propCoupon)
        ElMessage.success(`已选择 ${selectedProps.length} 个道具券`)
        propDialogVisible.value = false
    } else {
        ElMessage.warning('请选择道具券并设置数量')
    }
}

// 加载等级数据（编辑模式）
const loadLevelData = async () => {
    if (isEdit.value) {
        try {
            const id = route.params.id as string
            const res = await getMemberLevelDetail(id)
            const responseData = res as any
            
            if (responseData && responseData.code === 200 && responseData.data) {
                const data = responseData.data
                Object.assign(formData, {
                    levelCode: data.levelCode || '',
                    levelName: data.levelName || '',
                    memberLevel: data.memberLevel || 1,
                    growthValue: data.growthValue || 0,
                    consumptionAmount: data.consumptionAmount || 0,
                    sortOrder: data.sortOrder || '',
                    language: data.language || 'zh-CN',
                    consumptionAmountDesc: data.consumptionAmountDesc || '',
                    benefits: {
                        qa: false,
                        qaDiscount: '',
                        products: false,
                        productsDiscount: '',
                        services: false,
                        servicesDiscount: '',
                        coupon: false,
                        propCoupon: false
                    },
                    selectedCoupons: [],
                    selectedProps: []
                })
                
                // 处理benefits数据回显
                if (data.benefits && Array.isArray(data.benefits)) {
                    data.benefits.forEach((benefit: any) => {
                        switch (benefit.benefitType) {
                            case 1: // 问答
                                formData.benefits.qa = true
                                formData.benefits.qaDiscount = benefit.discountRate
                                break
                            case 2: // 商品
                                formData.benefits.products = true
                                formData.benefits.productsDiscount = benefit.discountRate
                                break
                            case 3: // 服务
                                formData.benefits.services = true
                                formData.benefits.servicesDiscount = benefit.discountRate
                                break
                            case 4: // 优惠券
                                formData.benefits.coupon = true
                                formData.selectedCoupons.push({
                                    id: benefit.benefitId,
                                    name: benefit.benefitName,
                                    quantity: benefit.discountRate
                                })
                                break
                            case 5: // 道具
                                formData.benefits.propCoupon = true
                                formData.selectedProps.push({
                                    id: benefit.benefitId,
                                    name: benefit.benefitName,
                                    quantity: benefit.discountRate
                                })
                                break
                        }
                    })
                }
                
                console.log('加载的等级数据:', data)
            } else {
                const errorMsg = (responseData && responseData.msg) || '获取等级详情失败'
                ElMessage.error(errorMsg)
            }
        } catch (error) {
            console.error('获取等级详情失败:', error)
            ElMessage.error('获取等级详情失败，请稍后重试')
        }
    }
}

onMounted(() => {
    loadLevelData()
})
</script>

<style scoped>
.level-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    gap: 12px;
}

/* 表单内容 */
.form-content {
    /* max-width: 1200px; */
}

.form-card {
    border-radius: 8px;
    background-color: #fff;
}

.level-form {
    padding: 20px;
}

.form-layout {
    display: flex;
    gap: 40px;
}

.form-left {
    flex: 1;
}


.form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}

.benefits-section {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.benefit-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.coupon-section {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 12px;
}

.coupon-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.selected-coupons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.prop-section {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 12px;
}

.prop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.selected-props {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.form-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
    justify-content: center;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__body) {
    padding: 0;
}

:deep(.el-form-item) {
    margin-bottom: 24px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-button) {
    border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .level-form-container {
        padding: 10px;
    }
    
    .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .form-content {
        max-width: 100%;
    }
    
    .level-form {
        padding: 15px;
    }
    
    .form-layout {
        flex-direction: column;
        gap: 20px;
    }
    
    
    .benefit-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
}
</style>
